package ai.taromed.vr

import android.content.pm.PackageManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

open class AppCompatActivityEx : AppCompatActivity() {

    companion object{
        const val REQUEST_CODE_PERMISSIONS = 2297;
    }


    private var mPermissionCallback:PermissionCallback? = null

    public interface PermissionCallback {
        fun onPermissionGranted()
        fun onPermissionDenied()
    }

    public fun requestPermissions(permissions:Array<String>, callback:PermissionCallback) {
        var allPermissionsGranted = true
        permissions.forEach {
            if (ActivityCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false
            }
        }
        if (allPermissionsGranted) {
            if (callback != null) {
                callback.onPermissionGranted();
            }
        }
        else {
            mPermissionCallback = callback;
            ActivityCompat.requestPermissions(this, permissions,
                REQUEST_CODE_PERMISSIONS);
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        var grantedAll = true
        if (requestCode == REQUEST_CODE_PERMISSIONS && grantResults.size == permissions.size) {
            grantResults.forEach {
                if (it != PackageManager.PERMISSION_GRANTED) {
                    grantedAll = false;
                }
            }
        }
        if (grantedAll) {
            if (mPermissionCallback != null) {
                mPermissionCallback!!.onPermissionGranted();
            }
        }
        else {
            Toast.makeText(this, "Request Permissions Failed", Toast.LENGTH_LONG).show();
            if (mPermissionCallback != null) {
                mPermissionCallback!!.onPermissionDenied();
            }
        }
    }


}